/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"C5DC509F-1035-43F5-BBDC-5C46260AB13A",variableType:4}
 */
var fcentro = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"546D87B4-59E4-4D1D-9A57-7178901A051B",variableType:4}
 */
var fcuenta = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"4C87AAC9-4E9D-40E0-81EC-0DD10F07A0FD",variableType:8}
 */
var fdif = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"969620D0-E178-4ABE-A661-0B3E0CC0E857",variableType:4}
 */
var fdivision = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"4159FCF8-6E05-4327-A87B-08FEAC5C4871",variableType:8}
 */
var fdolar;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"A58DA0C3-1BFF-4EE8-A260-CB1E9ABBCA67",variableType:4}
 */
var fImprime = 0;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"F2C445B4-2EB0-4552-92A3-5776E6E3C03D",variableType:4}
 */
var fSalir = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"1954E4AC-FBEC-4299-B75F-D03F62ED1D00",variableType:8}
 */
var ftotal = null;

/**
 * Callback method for when form is shown.
 *
 * @param {Boolean} [firstShow] form is shown first time after load
 * @param {JSEvent} [event] the event that triggered the action
 *
 * @properties={typeid:24,uuid:"C242D913-9272-4FBD-B94F-7B6B9C05DF47"}
 * @AllowToRunInFind
 */
function onShow(firstShow, event) {
	fSalir = 0
	databaseManager.setAutoSave(false)

    var pfecha 	= new Date(globals.gAnio,globals.gMes,0)
    fdolar 		= globals.gBuscarCotizacion(pfecha)
    globals.gtotal_debe  = 0
	globals.gtotal_haber = 0
	if (foundset.getSize() > 0)
	{
		if (limbo_cab_to_limbo.getSize() != 0) 
		{
		    limbo_cab_to_limbo.find()
		    limbo_cab_to_limbo.columna = "F"
		    limbo_cab_to_limbo.search()    
	    }
	}
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"BDD602F7-EFB8-4BCB-B662-E180B8684131"}
 */
function onAction_habilita(event) {
	elements.tabs_80.removeAllTabs()
	globals.gtotal_debe  = 0
	globals.gtotal_haber = 0
	if (globals.gMes == null || globals.gAnio == null) 
	{
		globals.DIALOGS.showWarningDialog("Aviso","Debe ingresar un período","Ok")
		return   		
	}
/*	var params = {
         processFunction: DifConversion,
         message: 'Generando Asiento...', 
         opacity: 0.5,
         paneColor: '#80ffff',
         textColor: '#0080ff',
         showCancelButton: false
	};*/
	try
	{
		//plugins.busy.block( params );
		fSalir = DifConversion()
	}
	catch (e)
	{
		globals.DIALOGS.showErrorDialog('Error','Error desconocido : ' + e,'OK')
	}
}

/**
 * @properties={typeid:24,uuid:"678C492E-47E3-4679-B848-68F45DC30742"}
 */
function GraboItem(ds_lista) {
	limbo_cab_to_limbo.newRecord()
	limbo_cab_to_limbo.cuentas_id = fcuenta
	limbo_cab_to_limbo.division   = fdivision
	limbo_cab_to_limbo.centro     = fcentro
	limbo_cab_to_limbo.leycod     = 0
	limbo_cab_to_limbo.leyenda    = "Por Diferencia de Conversion" 
	limbo_cab_to_limbo.importe    = 0
	var $leyenda = "Diferencia de Conversion"
	var $debe    = null
	var $haber   = null
	if (fdif < 0)
	{
		limbo_cab_to_limbo.columna = "D"
		limbo_cab_to_limbo.impodol = fdif * (-1)
		$debe = fdif * (-1)
		globals.gtotal_debe = globals.gtotal_debe + (fdif * (-1))
	}
	else 
	{
		limbo_cab_to_limbo.columna = "H"
		limbo_cab_to_limbo.impodol = fdif
		$haber = fdif
		globals.gtotal_haber += fdif
	} 
	var $reg = new Array(limbo_cab_to_limbo.limbo_to_cuentas.cuenta_impresion,fdivision,fcentro,$leyenda,$debe,$haber,limbo_cab_to_limbo.columna,fecha)
	ds_lista.addRow($reg)	
}

/**
 * Handle hide window.
 *
 * @param {JSEvent} [event] the event that triggered the action
 *
 * @returns {Boolean}
 *
 * @properties={typeid:24,uuid:"F47A8094-C2CC-4F24-B626-18072DC509AA"}
 */
function onHide(event) {	
	if (fSalir == 1)
	{	
		var res = globals.DIALOGS.showQuestionDialog('','Esta seguro que desea Salir?','SI','NO')    	
		if (res == 'NO')
		  {
			return false
		  }
		  else
		  {
	     	databaseManager.revertEditedRecords()
		    databaseManager.setAutoSave(true)
		    return true
	   	  }
	}
	return true
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"28226328-7892-441A-AA92-0F4C80D77749"}
 */
function onAction_cancelar(event) {
	onHide()
	globals.gtotal_debe  = 0
	globals.gtotal_haber = 0
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"93AEDE53-2AEB-4EC7-9F9C-04C6B778E009"}
 * @AllowToRunInFind
 */
function onAction_confirmar(event) {
	var res = globals.DIALOGS.showQuestionDialog('','Actualiza el asiento?','SI','NO')
	if (res == 'NO')
    {
       return 
    } 
	var error = 0
	
	for (var i = 1 ; i <= forms.dif_conversion_det.controller.getMaxRecordIndex(); i++)
	{
		forms.dif_conversion_det.controller.setSelectedIndex(i)
		
		if (forms.dif_conversion_det.cuentas_id == null || forms.dif_conversion_det.division == null || forms.dif_conversion_det.centro == null)
		{
			error = 1
			globals.DIALOGS.showWarningDialog("Aviso","Existen campos sin completar","Ok")					
			break
		}
	}	
	if (utils.numberFormat(globals.gtotal_debe,2) != utils.numberFormat(globals.gtotal_haber,2))
	{
		error = 1
		globals.DIALOGS.showWarningDialog("Aviso","El Total del Debe no coincide con el Total del Haber","Ok")
	}
	if (error == 0)  
	{
		/** @type {JSFoundSet<db:/contable/numcon>}*/
		var fs_numcon = databaseManager.getFoundSet('contable','numcon')
		var estado = fs_numcon.find()
		if (estado == false)
		{
			globals.DIALOGS.showWarningDialog("Aviso","Error al hacer el find","Ok")
			error = 1
		}
		fs_numcon.anio 		= globals.gMes
		fs_numcon.mes  		= globals.gAnio
		fs_numcon.empresa 	= globals.gUservID
		
		if (fs_numcon.search() == 0)
		{	
	        globals.DIALOGS.showWarningDialog("Aviso","Fecha inválida","Ok")
			error = 1
		}
		else
		{
			if (fs_numcon.marca_cierre == 1)
			{
				globals.DIALOGS.showWarningDialog("Aviso","Mes Cerrado","Ok")
				error = 1
			}
		}
	}
	if (error == 1)
	{
		globals.DIALOGS.showWarningDialog("Aviso","Asiento sin actualizar","Ok")		
	}
	else
	{
		numero     = fs_numcon.limbo
		provisorio = fs_numcon.limbo		
		moneda_carga = 2		
		total      = globals.gtotal_debe
		fs_numcon.limbo = fs_numcon.limbo + 1
		var estado = databaseManager.saveData()
		if (estado == false){
			globals.DIALOGS.showWarningDialog("Aviso","No se actualizaron los datos","Ok")
			databaseManager.revertEditedRecords()
			return
		}
		globals.DIALOGS.showWarningDialog("Aviso","Asiento actualizado","Ok")
		onShow()
	}
}

/**
 * @properties={typeid:24,uuid:"C55FBB98-3338-4A9B-8D81-3E39DDCB888D"}
 * @AllowToRunInFind
 */
function DifConversion() {
	/** @type {JSFoundSet<db:/contable/saldos>}*/
	var $saldos = databaseManager.getFoundSet('contable','saldos')	
	var estado = $saldos.find()
	if (estado == false)
	{
		globals.DIALOGS.showWarningDialog("Aviso","Error al hacer el find","Ok")
		//plugins.busy.unblock();
		return 0
	}
 
	$saldos.anio = '<' + globals.gAnio
	$saldos.saldos_to_cuentas.marca_mon = 'S'
	
	$saldos.newRecord()
	
	$saldos.anio 	= globals.gAnio
	$saldos.mes 	= '<=' + globals.gMes
	$saldos.saldos_to_cuentas.marca_mon = 'S'
	
	var $cuantos = $saldos.search()	
	if ($cuantos == 0)
	{
		globals.DIALOGS.showWarningDialog('Aviso','No hay saldos para cuentas monetarias','OK')
		//plugins.busy.unblock(); 
		return 0
	}
	$saldos.sort('cuentas_id asc, division asc, centro asc')
	globals.gmoneda_consulta = 2
	controller.newRecord()
	tipo_actualizacion 	= globals.z_conf_asiento_normal
	dolar  				= 1
	fecha  				= new Date(globals.gAnio,globals.gMes,0)
	hizo   				= globals.glegajo
	empresa   			= globals.gUservID
	moneda 				= "D"
	letra  				= " "		
	moneda_carga 		= 2
	texto 				= "Por Diferencia de Conversion"

	$cuantos = databaseManager.getFoundSetCount($saldos)
	var totpes = 0
	var totdol = 0
	globals.gtotal_debe  = 0
	globals.gtotal_haber = 0
	fdif      = 0
	ftotal    = 0
	fcuenta   = 0
	fdivision = 0
// Esto lo hago para poder imprimir	
    var $cols = new Array('cuenta_impresion','division','centro','leyenda','debe_pesos','haber_pesos','columna','fecha')
    var ds_lista = databaseManager.createEmptyDataSet(0,$cols)
	
	for (var i = 1 ; i <= $cuantos ; i++)
	{
		$saldos.setSelectedIndex(i)
		if (i == 1)
		{
		 	fcuenta   = $saldos.cuentas_id
		 	fdivision = $saldos.division
		 	fcentro   = $saldos.centro
		}
		if (fcuenta == $saldos.cuentas_id && fdivision == $saldos.division && fcentro == $saldos.centro)
		{
			totpes += $saldos.debe_pes - $saldos.haber_pes
			totdol += $saldos.debe_dol - $saldos.haber_dol
		}
		else 
		{
			var imp = totpes / fdolar
			var $pesosdol = imp.toFixed(2)*1
			fdif = $pesosdol - totdol
			ftotal += fdif
			if (fdif != 0) 
			{
				GraboItem(ds_lista)
			}
			totpes = 0
			totdol = 0
		 	fcuenta   = $saldos.cuentas_id
		 	fdivision = $saldos.division
		 	fcentro   = $saldos.centro
		}			
	}
	var imp = totpes / fdolar	
	var $pesosdol = imp.toFixed(2)*1
	fdif = $pesosdol - totdol
	ftotal += fdif
	if (fdif != 0) 
	{
		GraboItem(ds_lista)
	}
	if (ftotal != 0)
	{		
		/** @type {JSFoundSet<db:/contable/ctas_sis>}*/
		var fs_ctas_sis = databaseManager.getFoundSet('contable','ctas_sis')	
		var estado = fs_ctas_sis.find()
		if (estado == false)
		{
			globals.DIALOGS.showWarningDialog("Aviso","Error al hacer el find","Ok")
			//plugins.busy.unblock();
			return 0
		}
		fs_ctas_sis.sistema =  1
		fs_ctas_sis.codigo  = 27
		var estado = fs_ctas_sis.search()
		if (estado != 1)
		{
			globals.DIALOGS.showWarningDialog("Aviso","No ubica la cuenta","Ok")
			//plugins.busy.unblock(); 
			return 0
		}
		fs_ctas_sis.setSelectedIndex(1)
		limbo_cab_to_limbo.newRecord()
		limbo_cab_to_limbo.cuentas_id = fs_ctas_sis.cuentas_id
		limbo_cab_to_limbo.division   = fs_ctas_sis.division
		limbo_cab_to_limbo.centro     = fs_ctas_sis.centro
		limbo_cab_to_limbo.leycod     = 0
		limbo_cab_to_limbo.leyenda    = "Diferencia de Conversion"
		limbo_cab_to_limbo.importe    = 0
		var $leyenda = "Diferencia de Conversion"
		var $debe    = null
		var $haber   = null 		
		if (ftotal < 0)
		{
			limbo_cab_to_limbo.columna = "H"
			limbo_cab_to_limbo.impodol = ftotal * (-1)
			$haber = ftotal * (-1)
			globals.gtotal_haber = globals.gtotal_haber + (ftotal * (-1))
		}
		else 
		{
			limbo_cab_to_limbo.columna = "D"
			limbo_cab_to_limbo.impodol = ftotal
			$debe = ftotal
			globals.gtotal_debe += ftotal
		}
		var $reg = new Array(limbo_cab_to_limbo.limbo_to_cuentas.cuenta_impresion,fdivision,fcentro,$leyenda,$debe,$haber,limbo_cab_to_limbo.columna,fecha)
		ds_lista.addRow($reg)
		var $reg = new Array("TOTAL ASIENTO",null,null,null,globals.gtotal_debe,globals.gtotal_haber,"Z",fecha)
 		ds_lista.addRow($reg)
	}
	//forms.dif_conversion_impresion.controller.loadRecords(forms.dif_conversion_det.foundset)
	//plugins.busy.unblock();

	var frm = solutionModel.getForm('dif_conversion_impresion')
	var $tipos = new Array(JSColumn.TEXT,JSColumn.INTEGER,JSColumn.INTEGER,JSColumn.TEXT,JSColumn.NUMBER,JSColumn.NUMBER,JSColumn.TEXT,JSColumn.DATETIME)
	var dSource = ds_lista.createDataSource('conversion',$tipos)
	frm.dataSource = dSource
	forms.dif_conversion_impresion.controller.sort("columna asc")
	forms.dif_conversion_impresion.controller.recreateUI()
	elements.tabs_80.addTab(forms.dif_conversion_det,null,null,null,null,null,null,'limbo_cab_to_limbo')
	return 1
}

/**
 * Handle changed data.
 *
 * @param {String} oldValue old value
 * @param {String} newValue new value
 * @param {JSEvent} event the event that triggered the action
 *
 * @returns {Boolean}
 *
 * @properties={typeid:24,uuid:"E18FEC1E-5E90-49D9-9C7D-0841F3923C26"}
 */
function onDataChangeFecha(oldValue, newValue, event) {
	globals.gMesHasta	= newValue.substring(0,newValue.indexOf('|'))
	globals.gAnioHasta	= newValue.substring(newValue.indexOf('|')+1,newValue.length)
	return true
}
